﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ecodex.RestAPI;
using Ecodex.RestAPI.Exceptions;
using Ecodex.RestAPI.Models;

namespace EcodexIntegrationSample.Controllers
{
    class frmObtenerUltimosDocumentosTimbradosController
    {
        View.IfrmObtenerUltimosDocumentosTimbrados _view;

        public frmObtenerUltimosDocumentosTimbradosController(View.IfrmObtenerUltimosDocumentosTimbrados view)
        {
            _view = view;
            _view.onBuscarUltimosDocumentosTimbrados += _view_onBuscarUltimosDocumentosTimbrados;
        }

        void _view_onBuscarUltimosDocumentosTimbrados(object sender, EventArgs e)
        {
            try
            {
                Utils.Utilerias util = new Utils.Utilerias();

                Uri url = new Uri(util.urlApi);
                RestApi api = new RestApi(url);
                var token = api.GetToken(_view.RFCEmisor, util.INTEGRATOR_ID);
                foreach (var item in api.GetDocumentos(token))
                {
                    _view.Respuesta += String.Format("{0} : {1} : {2} \n", item.TipoDocumento, item.UUID, item.FechaTimbrado);
                }
            }
            catch (FallaAplicacion ex)
            {
                using (var errorForm = new Forms.Error(TranslateErrorAPI.ToServiceError(_view.RFCEmisor, ex)))
                {
                    errorForm.ShowDialog();
                }
            }
            catch (FallaSesion fallaSession)
            {                
                _view.ShowSessionError(TranslateErrorAPI.ToSessionError(_view.RFCEmisor, fallaSession));
            }
            catch (FallaValidacion fallaValidacion)
            {
                using (var errorForm = new Forms.Error(TranslateErrorAPI.ToServiceError(_view.RFCEmisor, fallaValidacion)))
                {
                    errorForm.ShowDialog();
                }
            }
        }
    }
}

